package com.yyx.jupiter.component;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class CacheManager {
    @Resource
    RedisClient redisClient;

    private Cache<String, Object> hotRecallCache = null;
    private Cache<Integer, String> bucket2StrategyCache = null;

    @PostConstruct
    public void initHotRecallCache() {
        hotRecallCache = CacheBuilder.newBuilder()
                //设置并发级别，并发级别是指可以同时写缓存的线程数
                .concurrencyLevel(1)
                //设置缓存容器的初始容量为10
                .initialCapacity(10)
                //设置缓存最大容量为100，超过100之后就会按照LRU最近虽少使用算法来移除缓存项
                .maximumSize(100)
                //设置写缓存后n秒钟过期
                .expireAfterWrite(1, TimeUnit.HOURS)
                //设置缓存
                .build();
    }

    public Object getHotRecallCache(String sceneId) {
        Object hotRecall = hotRecallCache.getIfPresent(sceneId);
        if (hotRecall == null) {
            String redisKey = String.format("yyx:hotrecall:%s", sceneId);
            hotRecall = redisClient.get(redisKey, String.class);

            if (hotRecall == null) {
                return null;
            } else {
                hotRecallCache.put(sceneId, hotRecall);
            }
        }
        return hotRecall;
    }
}
